<!DOCTYPE html>
<html  lang="zh-CN" >
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, maximum-scale=5, viewport-fit=cover">
    <title>knockoutjs十一  value绑定 | 在路上</title>
    <meta name="description" content="knockoutjs  value绑定">
<meta property="og:type" content="article">
<meta property="og:title" content="knockoutjs十一  value绑定">
<meta property="og:url" content="http://www.lushunming.com.cn/2016/03/11/web/2016-03-11-11value/index.html">
<meta property="og:site_name" content="在路上">
<meta property="og:description" content="knockoutjs  value绑定">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2016-03-10T16:00:00.000Z">
<meta property="article:modified_time" content="2019-11-24T07:17:53.638Z">
<meta property="article:author" content="machine">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="knockoutjs">
<meta name="twitter:card" content="summary">

    
    <link rel="icon" href="/images/favicon.ico" type="image/x-icon">

    
<link rel="stylesheet" href="/css/common.min.css">



    
    
    
        <link href="//cdn.jsdelivr.net/npm/gitalk@1.4.0/dist/gitalk.min.css" rel="stylesheet">
    
    
        <link href="//cdn.jsdelivr.net/npm/lightgallery.js@1.1.3/dist/css/lightgallery.min.css" rel="stylesheet">
    
    
    
<link rel="stylesheet" href="/css/iconfont.min.css">

    
<meta name="generator" content="Hexo 5.1.1"></head>

    <body>
        <header class="header header-fixture">
    <div class="profile-search-wrap flex sm:block">
        
        
        <div class="profile sm:text-center md:px-1 lg:px-3 sm:pb-4 sm:pt-6">
            <a id="avatar" role="link" href="https://www.lushunming.com.cn" class="inline-block lg:w-16 lg:h-16 w-8 h-8 m-2" target="_self" rel="noopener" rel="noreferrer" >
                <img src="/images/avatar.jpg" class="rounded-full" alt="avatar">
            </a>
            <h2 id="name" class="hidden lg:block">lushunming</h2>
            <h3 id="title" class="hidden xl:block">前码农</h3>
            
            <small id="location" class="hidden lg:block">
                <i class="iconfont icon-map-icon"></i>
                泰州
            </small>
            
        </div>
        
        
<div class="search flex-1 flex lg:inline-block sm:hidden lg:px-4 lg:mt-2 lg:mb-4 lg:w-full">
    <form id="search-form" class="my-auto flex-1 lg:border lg:border-solid lg:border-gray-200">
        <div class="input-group table bg-gray-100 lg:bg-white w-full">
            <input id="search-input" type="text" placeholder="搜索" class="inline-block w-full bg-gray-100 lg:bg-white">
            <span class="table-cell">
                <button name="search tigger button" disabled>
                    <i class="iconfont icon-search m-2"></i>
                </button>
            </span>
        </div>
    </form>
        
<script id="search-teamplate" type="text/html" data-path="/content.json">
    <div>
        <div class="search-header bg-gray-400">
            <input id="actual-search-input" model="keyword" ref="input" class="inline-block w-full h-10 px-2 py-1" placeholder="搜索" type="text">
        </div>
        <div class="search-result bg-gray-200">
            {{#each searchPosts}}
            <a href="/{{ path }}" class="result-item block px-2 pb-3 mb-1 pt-1 hover:bg-indigo-100">
                <i class="iconfont icon-file"></i>
                <h1 class="result-title inline font-medium text-lg">{{ title }}</h1>
                <p class="result-content text-gray-600 text-sm">{{{ text }}}</p>
            </a>
            {{/each}}
        </div>
    </div>
</script>

</div>


        <button name="menu toogle button" id="menu-toggle-btn" class="block sm:hidden p-3" role="button" aria-expanded="false">
            <i class="iconfont icon-hamburger"></i>
        </button>
    </div>
    <nav id="menu-nav" class="hidden sm:flex flex-col">
        
        
            <div class="menu-item menu-home" role="menuitem">
                <a href="/.">
                    <i class="iconfont icon-home" aria-hidden="true"></i>
                    <span class="menu-title">首页</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-archives" role="menuitem">
                <a href="/archives">
                    <i class="iconfont icon-archive" aria-hidden="true"></i>
                    <span class="menu-title">归档</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-categories" role="menuitem">
                <a href="/categories">
                    <i class="iconfont icon-folder" aria-hidden="true"></i>
                    <span class="menu-title">分类</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-tags" role="menuitem">
                <a href="/tags">
                    <i class="iconfont icon-tag" aria-hidden="true"></i>
                    <span class="menu-title">标签</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-repository" role="menuitem">
                <a href="/repository">
                    <i class="iconfont icon-project" aria-hidden="true"></i>
                    <span class="menu-title">项目</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-links" role="menuitem">
                <a href="/links">
                    <i class="iconfont icon-friend" aria-hidden="true"></i>
                    <span class="menu-title">友链</span>
                </a>
            </div>
        
        
            <div class="menu-item menu-about" role="menuitem">
                <a href="/about">
                    <i class="iconfont icon-cup" aria-hidden="true"></i>
                    <span class="menu-title">关于</span>
                </a>
            </div>
        
        
<div class="social-links flex sm:flex-col lg:hidden mt-5">
    
        <span class="social-item text-center">
            <a target="_blank" rel="noopener" href="https://github.com/lushunming">
                <i class="iconfont social-icon icon-github"></i>
                <span class="menu-title hidden lg:inline">menu.github</span>
            </a>
        </span>
    
        <span class="social-item text-center">
            <a href="/atom.xml">
                <i class="iconfont social-icon icon-rss"></i>
                <span class="menu-title hidden lg:inline">menu.rss</span>
            </a>
        </span>
    
</div>


    </nav>
</header>

        <section class="main-section">
            
    <main class="flex-1 px-4 py-12 md:px-5 lg:px-8 lg:py-4 relative min-h-screen">
    

    <article class="content article article-archives article-type-list" itemscope="">
        <header class="article-header">
            
    
        <h1 class="article-title text-lg" itemprop="name">
            knockoutjs十一  value绑定
        </h1>
    



            <p class="article-meta mb-3 text-xs">
                <span class="article-date">
    <i class="iconfont icon-calendar-check"></i>
	<a href="/2016/03/11/web/2016-03-11-11value/" class="article-date">
	  <time datetime="2016-03-10T16:00:00.000Z" itemprop="datePublished">3月 11</time>
	</a>
</span>

                
    <span class="article-category">
    <i class="iconfont icon-folder"></i>
    <a class="article-category-link" href="/categories/web/">web</a>
  </span>


                
    <span class="article-tags">
    <i class="iconfont icon-tag"></i>
    <a class="article-tag-none-link" href="/tags/javascript/" rel="tag">javascript</a>, <a class="article-tag-none-link" href="/tags/knockoutjs/" rel="tag">knockoutjs</a>
  </span>


                <span class="_partial/post-comment"><i class="icon icon-comment"></i>
                    <a href="/2016/03/11/web/2016-03-11-11value/#comments" class="article-comment-link">
                        评论
                    </a>
                </span>
                

            </p>
        </header>
        <div class="marked-body article-body">
            <h1>knockoutjs十一  value绑定</h1>
<p>我自己都没有想到自己会写一个博客写到第十一篇，而且看过我博客的人也越来越多，我在这期间也学会了更多，这个系列的博客估计在十五篇左右就结束了，我准备把经常用到的都写完，还又一些更高级的就不写了，毕竟我因为离开了之前的公司，不再用这个框架了，以后可能会写一些小的demo，希望大家到时候还能捧场。</p>
<p>废话不多说：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>Login name:</span><br><span class="line">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">data-bind</span>=<span class="string">&quot;value: userName&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">p</span>&gt;</span>Password:</span><br><span class="line">            <span class="tag">&lt;<span class="name">input</span> <span class="attr">type</span>=<span class="string">&quot;password&quot;</span> <span class="attr">data-bind</span>=<span class="string">&quot;value:userPassword,valueUpdate:&#x27;keyup&#x27;&quot;</span> /&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">         <span class="tag">&lt;<span class="name">a</span> <span class="attr">class</span>=<span class="string">&quot;btn btn-primary&quot;</span> <span class="attr">data-bind</span>=<span class="string">&quot;click:getInputValues&quot;</span>&gt;</span>获取输入框的值<span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="javascript">        <span class="function"><span class="keyword">function</span> <span class="title">Model</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line"><span class="javascript">            <span class="keyword">var</span> self = <span class="built_in">this</span>;</span></span><br><span class="line"><span class="javascript">            self.userName = ko.observable(<span class="string">&quot;&quot;</span>);</span></span><br><span class="line"><span class="javascript">            self.userPassword = ko.observable(<span class="string">&quot;&quot;</span>);</span></span><br><span class="line"></span><br><span class="line">          </span><br><span class="line"><span class="javascript">            self.getInputValues = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span></span><br><span class="line">               </span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(<span class="string">&quot;firstValue--&quot;</span> + self.firstValue());</span></span><br><span class="line"><span class="javascript">                <span class="built_in">console</span>.log(<span class="string">&quot;secondValue--&quot;</span> + self.secondValue);</span></span><br><span class="line"></span><br><span class="line">            &#125;;</span><br><span class="line">        &#125;</span><br><span class="line"><span class="javascript">        <span class="keyword">var</span> model = <span class="keyword">new</span> Model();</span></span><br><span class="line">        ko.applyBindings(model);</span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>今天的value绑定确实使用的比较多的，因为表单中基本都是，所以需要详细介绍，这是一个简单的例子，value绑定主要用于 <code>&lt;input&gt;, &lt;select&gt; 和&lt;textarea&gt;</code>这几个元素，而radio button 和checkbox使用checked，将会在下一次讲解。</p>
<p>1）value绑定的主要参数将会被设置为元素的value属性，这个值可以用jquery的val（）方法获取，而且这个值会覆盖你原有的value属性，如果你这样使用</p>
<p><code> &lt;input value=&quot;1&quot; data-bind=&quot;value:number&quot;/&gt;</code></p>
<p>这样你的value=1会被绑定覆盖。<br>
2）valueUpdate是第二个参数，ko实在change事件的时候检测input属性的改变，但是你可以通过valueUpdate来改变检测的时机，</p>
<ol>
<li>
<p>“input” - 这是当input的值改变的时候触发，但是只支持一些现代浏览器比如ie9+；</p>
</li>
<li>
<p>“keyup” - 在你松开一个按键的时候触发改变你的viewmodel</p>
</li>
<li>
<p>“keypress” -  这是当你按下一个键的时候触发，但是和keyup不同的是，如果一直按着键，他会不断重复的触发。</p>
</li>
<li>
<p>“afterkeydown” 在你按一个键同时触发（官方用的时as soon as），他在你输入的同时，异步的改变viewmodel，但是在一些手机浏览器中不支持。</p>
</li>
</ol>
<p>3）valueAllowUnset这个只适合在select元素中使用。</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">p</span>&gt;</span></span><br><span class="line">Select a country:</span><br><span class="line"><span class="tag">&lt;<span class="name">select</span> <span class="attr">data-bind</span>=<span class="string">&quot;options: countries,</span></span></span><br><span class="line"><span class="tag"><span class="string">                   optionsCaption: &#x27;Choose one...&#x27;,</span></span></span><br><span class="line"><span class="tag"><span class="string">                   value: selectedCountry,</span></span></span><br><span class="line"><span class="tag"><span class="string">                   valueAllowUnset: true&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">select</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line"> </span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript"><span class="keyword">var</span> viewModel = &#123;</span></span><br><span class="line"><span class="javascript">    countries: [<span class="string">&#x27;Japan&#x27;</span>, <span class="string">&#x27;Bolivia&#x27;</span>, <span class="string">&#x27;New Zealand&#x27;</span>],</span></span><br><span class="line"><span class="javascript">    selectedCountry: ko.observable(<span class="string">&#x27;Latvia&#x27;</span>)</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>这个例子中，使用selectedCountry设置了一个原始选中值’Latvia’，可是在下拉选项中并没有这个值，所以ko把他重置为undefinded，那么就与’Choose one…‘相匹配，就会默认选中’Choose one…’。这回在selectOption中详细讲解。</p>
<p>以下有几点注意</p>
<ul>
<li>在使用<code>&lt;input type=&quot;text&quot; /&gt;</code> or<br>
<code>&lt;textarea&gt;</code>时候，官方建议使用textInput绑定，这是一个新的绑定，在我之前使用的时候还没有。</li>
<li>使用observable和non-observable绑定的区别：</li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- Two-way binding. Populates textbox; syncs both ways. --&gt;</span> </span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>First value: <span class="tag">&lt;<span class="name">input</span> <span class="attr">data-bind</span>=<span class="string">&quot;value: firstValue&quot;</span> /&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">p</span>&gt;</span>  </span><br><span class="line">       <span class="comment">&lt;!--One-way binding. Populates textbox; syncs only from textbox to model.--&gt;</span> </span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>Second value: <span class="tag">&lt;<span class="name">input</span> <span class="attr">data-bind</span>=<span class="string">&quot;value: secondValue&quot;</span> /&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">p</span>&gt;</span>  </span><br><span class="line">       <span class="comment">&lt;!-- No binding. Populates textbox, but doesn&#x27;t react to any changes.--&gt;</span> </span><br><span class="line">       <span class="tag">&lt;<span class="name">p</span>&gt;</span>Third value: <span class="tag">&lt;<span class="name">input</span> <span class="attr">data-bind</span>=<span class="string">&quot;value: secondValue.length &gt; 8&quot;</span> /&gt;</span></span><br><span class="line">       <span class="tag">&lt;/<span class="name">p</span>&gt;</span>  </span><br><span class="line">       <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span>&gt;</span></span><br><span class="line"><span class="javascript">          <span class="keyword">var</span> viewModel = &#123;</span></span><br><span class="line"><span class="javascript">              firstValue: ko.observable(<span class="string">&quot;hello&quot;</span>), <span class="comment">// Observable</span></span></span><br><span class="line"><span class="javascript">              secondValue: <span class="string">&quot;hello, again&quot;</span>         <span class="comment">// Not observable</span></span></span><br><span class="line">          &#125;;</span><br><span class="line">      <span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>
<ul>
<li>使用双向绑定，那么value和model中一个改变，另一个也会改变。但是使用的单向绑定，那么只会在初始化的时候给元素value赋值，在编辑的时候，会更新这个元素的value属性，但是当你的value属性改变的时候，model是不能检测到的，因为是一个单向绑定。如果绑定的不是一个简单的值，而是一个方法调用的结果，ko会用这个结果初始化元素的value属性，但是当在编辑表单的时候，不会改变元素的value属性，这种情况是一个一次性赋值，而不是一个能反映出改变的绑定。</li>
</ul>
<p>今天的就讲解完了，代码托管在https://github.com/lushunming/knockoutJSDemo.git可以直接克隆。希望大家有意见可以留言，有疑问或者错误可以加我的qq1357197829和我交流。</p>

        </div>
        
<blockquote class="copyright">
    <p><strong>本文链接 : </strong><a class="permalink" href="http://www.lushunming.com.cn/2016/03/11/web/2016-03-11-11value/">http://www.lushunming.com.cn/2016/03/11/web/2016-03-11-11value/</a></p>
    <p><strong>This article is available under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener noreferrer">Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0)</a> License</strong></p>
</blockquote>


    </article>
    
    <section id="comments">
        

        
    </section>


    

</main>


<aside style="" id="sidebar" class="aside aside-fixture">
    <div class="toc-sidebar">
        <nav id="toc" class="article-toc">
            <h3 class="toc-title">文章目录</h3>
            <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link"><span class="toc-number">1.</span> <span class="toc-text">knockoutjs十一  value绑定</span></a></li></ol>
        </nav>
    </div>
</aside>





        </section>
        <footer class="hidden lg:block fixed bottom-0 left-0 sm:w-1/12 lg:w-1/6 bg-gray-100 z-40">
    
    <div class="footer-social-links">
        
            <a target="_blank" rel="noopener" href="https://github.com/lushunming">
                <i class="iconfont icon-github"></i>
            </a>
        
            <a href="/atom.xml">
                <i class="iconfont icon-rss"></i>
            </a>
        
    </div>
    
    
</footer>

        <div id="mask" class="hidden mask fixed inset-0 bg-gray-900 opacity-75 z-40"></div>
        <div id="search-view-container" class="hidden shadow-xl"></div>
        
<script src="/js/dom-event.min.js"></script>

<script src="//cdn.jsdelivr.net/npm/yox@1.0.0-alpha.121/dist/standard/prod/yox.min.js"></script>


<script src="/js/search.min.js"></script>


    <script src="//cdn.jsdelivr.net/npm/gitalk@1.5.2/dist/gitalk.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/blueimp-md5@2.10.0/js/md5.min.js"></script>
<script type="text/javascript">
    var gitalk = new Gitalk({
        clientID: 'd76d74420825181b7018',
        clientSecret: '8b9c3676695fa33d6b10d9697a96ef27c8301930',
        repo: 'blog-comment',
        owner: 'lushunming',
        admin: ['lushunming'],
        id: md5(location.pathname),
        distractionFreeMode: true
    })
    gitalk.render('comments')
</script>



    <script src="//cdn.jsdelivr.net/npm/lightgallery.js@1.1.3/dist/js/lightgallery.min.js"></script>
    
<script src="/js/light-gallery.min.js"></script>





    </body>
</html>
